import React, { Component } from 'react';
import { Form, Icon, Input, Button, Alert } from 'antd';
import axios from '../../utils/axios';
import './login.less';

const FormItem = Form.Item;

class NormalLoginForm extends Component {

  constructor(props) {
    super(props)
    this.state = {
      submitLoading: false,
      submitError: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        this.setState({
          submitLoading: true
        });
        const param = {
          username: values.username,
          password: values.password
        };
        const response = await axios.post('/api/login', param);
        this.setState({
          submitLoading: false
        });
        const { success } = response.data;
        if (success) {
          this.props.history.push('/dashboard');
        } else {
          this.setState({
            submitError: true
          });
        }
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="login-wrap">
        <div className="logo-wrap">
          <img alt="logo" className="logo-wrap-logo" src={require('../../style/images/logo.png')} />
          <span className="logo-wrap-text">我的经管</span>
        </div>
        <Form onSubmit={this.handleSubmit} className="login-form">
          {
            this.state.submitError &&
            <FormItem>
              <Alert message="用户名或密码错误，请重新输入" type="error" showIcon/>
            </FormItem>
          }
          <FormItem>
            {getFieldDecorator('username', {
              rules: [{ required: true, message: '请输入用户名!' }],
            })(
              <Input size="large" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('password', {
              rules: [{ required: true, message: '请输入密码!' }],
            })(
              <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
            )}
          </FormItem>
          <FormItem>
            <a className="login-form-forgot" href="">忘记密码</a>
            <Button loading={this.state.submitLoading} size="large" type="primary" htmlType="submit" className="login-form-button">
              登录
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const Login = Form.create()(NormalLoginForm);

export default Login;

